package com.aiyige.utils.widget.articleview;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.aiyige.R;
import com.aiyige.page.publish.info.model.TextNode;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.VideoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.articleview.adapter.ArticleAdapter;
import com.aiyige.utils.widget.articleview.event.EventArticleContentChanged;
import com.aiyige.utils.widget.articleview.event.EventArticleTextNodeFocusChanged;
import com.aiyige.utils.widget.articleview.event.EventArticleTextNodeTextChanged;
import com.aiyige.utils.widget.articleview.model.ArticleNode;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.LinkedList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by zhuyakun on 2018/3/13.
 */

public class ArticleView extends FrameLayout implements View.OnClickListener {
    public static final int REQUEST_CODE_SELECT_PHOTO = 0xbacd;
    public static final int REQUEST_CODE_SELECT_VIDEO = 0xbace;

    RecyclerView articleRv;
    ArticleAdapter articleAdapter;
    ViewGroup controlPanel;
    View photoLayout;
    View videoLayout;
    View fontLayout;
    EditTextStyleBottomDialog editTextStyleBottomDialog;
    FragmentActivity activity;

    public ArticleView(@NonNull Context context) {
        super(context);
        init();
    }

    public ArticleView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ArticleView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void noVideo(){
        videoLayout.setVisibility(GONE);
    }

    public void noPhoto(){
        photoLayout.setVisibility(GONE);
    }



    void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.aritcle_view, this, true);
        photoLayout = findViewById(R.id.photoLayout);
        videoLayout = findViewById(R.id.videoLayout);
        fontLayout = findViewById(R.id.fontLayout);
        photoLayout.setOnClickListener(this);
        videoLayout.setOnClickListener(this);
        fontLayout.setOnClickListener(this);
        controlPanel = (ViewGroup) findViewById(R.id.controlPanel);
        articleRv = (RecyclerView) findViewById(R.id.articleRv);
        articleRv.setLayoutManager(new LinearLayoutManager(getContext()));
        articleAdapter = new ArticleAdapter();
        articleAdapter.bindToRecyclerView(articleRv);
        //addFooter(R.layout.article_view_footer);
        editTextStyleBottomDialog = EditTextStyleBottomDialog.newInstance();
        editTextStyleBottomDialog.setListener(new EditTextStyleBottomDialog.Listener() {
            @Override
            public void onSelect(int position, int textStyle) {
                try {
                    ArticleNode textNode = articleAdapter.getItem(position);
                    textNode.setTextStyle(textStyle);
                    articleAdapter.setData(position, textNode);
                } catch (Exception e) {

                }
            }
        });
        articleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        deleteNode(position);
                        break;
                }
            }
        });
    }

    public View addHeader(int headLayoutResId) {
        View header = LayoutInflater.from(getContext()).inflate(headLayoutResId, (ViewGroup) articleRv.getParent(), false);
        articleAdapter.addHeaderView(header);
        return header;
    }

    public View addFooter(int footerLayoutResId) {
        View footer = LayoutInflater.from(getContext()).inflate(footerLayoutResId, (ViewGroup) articleRv.getParent(), false);
        articleAdapter.addFooterView(footer);
        return footer;
    }

    public void setData(List<ArticleNode> data) {
        if (!ListUtil.isEmpty(data)) {
            if (data.get(0).getType() != ArticleNode.NODE_TYPE_TEXT) {
                data.add(0, ArticleNode.newBuilder()
                        .type(ArticleNode.NODE_TYPE_TEXT)
                        .textStyle(TextNode.TEXT_STYLE_MAIN_BODY)
                        .build());
            }
            articleAdapter.setNewData(data);
        } else {
            articleAdapter.addData(ArticleNode.newBuilder()
                    .type(ArticleNode.NODE_TYPE_TEXT)
                    .textStyle(TextNode.TEXT_STYLE_MAIN_BODY)
                    .build());
        }
    }

    public void deleteNode(int position) {
        articleAdapter.remove(position);
        while (true) {
            ArticleNode node = articleAdapter.getItem(position);
            if (node != null && node.getType() == ArticleNode.NODE_TYPE_TEXT && TextUtils.isEmpty(node.getText())) {
                articleAdapter.remove(position);
            } else {
                break;
            }
        }
        articleAdapter.notifyItemChanged(articleAdapter.getHeaderLayoutCount());
        notifyArticleContentChanged();
    }

    public void insertNodes(int startPosition, List<ArticleNode> articleNodes) {
        if (articleAdapter.getFocusdTextNodePosition() != null) {
            ArticleNode textNode = articleAdapter.getFocusedTextNode();
            EditText editText = articleAdapter.getFocusedTextNodeEditText();
            int selectionStart = editText.getSelectionStart();
            String textPiece = editText.getText().toString().substring(selectionStart);
            editText.getEditableText().delete(selectionStart, editText.getEditableText().length());
            int upLimit = articleNodes.size() - 1;
            for (int i = 0; i < upLimit; ++i) {
                articleAdapter.addData(startPosition++, articleNodes.get(i));
                articleAdapter.addData(startPosition++, ArticleNode.newBuilder()
                        .textStyle(textNode.getTextStyle())
                        .type(ArticleNode.NODE_TYPE_TEXT)
                        .build());
            }
            articleAdapter.addData(startPosition++, articleNodes.get(articleNodes.size() - 1));
            articleAdapter.addData(startPosition++,
                    ArticleNode.newBuilder()
                            .text(textPiece)
                            .type(ArticleNode.NODE_TYPE_TEXT)
                            .textStyle(textNode.getTextStyle())
                            .build());
            notifyArticleContentChanged();
            articleAdapter.notifyItemChanged(articleAdapter.getHeaderLayoutCount());
        }
    }

    public void notifyArticleContentChanged() {
        EventBus.getDefault().post(new EventArticleContentChanged());
    }

    public void onCreate(FragmentActivity activity) {
        this.activity = activity;
        try {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        } catch (Exception e) {

        }
    }


    public void onDestroy() {
        try {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
        } catch (Exception e) {

        }
    }

    public boolean isEmpty() {
        List<ArticleNode> data = getData();
        outerLoop:
        for (ArticleNode node : data) {
            switch (node.getType()) {
                case ArticleNode.NODE_TYPE_TEXT:
                    if (!TextUtils.isEmpty(node.getText())) {
                        return false;
                    }
                    break;
                default:
                    return false;
            }
        }
        return true;
    }

    public List<ArticleNode> getData() {
        return articleAdapter.getData();
    }

    @Subscribe
    public void onEvent(EventArticleTextNodeFocusChanged event) {
        if (event.isFocused()) {
            controlPanel.setVisibility(View.VISIBLE);
        } else {
            controlPanel.setVisibility(View.GONE);
        }
    }

    @Subscribe
    public void onEvent(EventArticleTextNodeTextChanged event) {
        notifyArticleContentChanged();
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SELECT_PHOTO: {
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    List<ArticleNode> photoNodeList = new LinkedList<>();
                    for (LocalMedia localMedia : selectList) {
                        photoNodeList.add(ArticleNode.newBuilder()
                                .type(ArticleNode.NODE_TYPE_PHOTO)
                                .url(localMedia.getPath())
                                .build());
                    }
                    int startPosition = articleAdapter.getFocusdTextNodePosition() + 1;
                    insertNodes(startPosition, photoNodeList);
                }
                break;
            }

            case REQUEST_CODE_SELECT_VIDEO: {
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        List<ArticleNode> videoNodeList = new LinkedList<>();
                        for (LocalMedia localMedia : selectList) {
                            videoNodeList.add(ArticleNode.newBuilder()
                                    .type(ArticleNode.NODE_TYPE_VIDEO)
                                    .url(localMedia.getPath())
                                    .duration(localMedia.getDuration() * 1000)
                                    .size(FileUtil.getFileSize(localMedia.getPath()))
                                    .build());
                        }
                        new AsyncTask<List<ArticleNode>, Object, List<ArticleNode>>() {
                            LoadingDialog loadingDialog;

                            @Override
                            protected void onPreExecute() {
                                loadingDialog = LoadingDialog.newBuilder()
                                        .with(ArticleView.this.getContext())
                                        .message(R.string.text_process)
                                        .show();
                            }

                            @Override
                            protected List<ArticleNode> doInBackground(List<ArticleNode>... params) {
                                List<ArticleNode> itemList = params[0];
                                for (ArticleNode item : itemList) {
                                    item.setCoverUrl(VideoUtil.getVideoCover(item.getUrl(), 0));
                                }
                                return itemList;
                            }

                            @Override
                            protected void onPostExecute(List<ArticleNode> list) {
                                loadingDialog.dismiss();
                                int startPosition = articleAdapter.getFocusdTextNodePosition() + 1;
                                List<ArticleNode> nodeList = new LinkedList<>();
                                for (ArticleNode item : list) {
                                    nodeList.add(item);
                                }
                                insertNodes(startPosition, nodeList);
                            }
                        }.execute(videoNodeList);
                    }
                }
                break;
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.photoLayout:
                if (!checkVideoPhotoNodeNum()) {
                    ToastX.show(R.string.too_much_video_or_photo_in_article);
                    break;
                }
                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofImage())
                        .minSelectNum(1)
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_SELECT_PHOTO);
                break;
            case R.id.videoLayout:
                if (!checkVideoPhotoNodeNum()) {
                    ToastX.show(R.string.too_much_video_or_photo_in_article);
                    break;
                }
                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofVideo())
                        .isCamera(false)
                        .previewImage(false)
                        .previewVideo(false)
                        .minSelectNum(1)
                        .selectionMode(PictureConfig.SINGLE)
                        .maxSize(PublishUtil.MAX_PUBLISH_VIDEO_SIZE)
                        .forResult(REQUEST_CODE_SELECT_VIDEO);
                break;
            case R.id.fontLayout:
                ArticleNode textNode = articleAdapter.getFocusedTextNode();
                if (textNode != null) {
                    editTextStyleBottomDialog.setPosition(articleAdapter.getFocusdTextNodePosition());
                    editTextStyleBottomDialog.setTextStyle(textNode.getTextStyle());
                    editTextStyleBottomDialog.show(activity.getSupportFragmentManager(), "");
                }
                break;
        }
    }

    public boolean checkVideoPhotoNodeNum() {
        int count = 0;
        for (ArticleNode node : articleAdapter.getData()) {
            switch (node.getType()) {
                case ArticleNode.NODE_TYPE_PHOTO:
                case ArticleNode.NODE_TYPE_VIDEO:
                    count++;
                    break;
            }
        }
        return count < PublishUtil.MAX_INFO_VIDEO_PHOTO_NUM;
    }
}
